package youxiao.bytezon.services;

import java.math.BigDecimal;
import java.time.LocalDate;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import youxiao.bytezon.models.CourseDetail;
import youxiao.bytezon.models.Teacher;
import youxiao.bytezon.models.TeacherLessonPremium;
import youxiao.bytezon.repositories.CourseDetailRepository;

@Service
public class TeacherLessonPremiumService {
	
	@Autowired CourseDetailRepository courseDetailRepository;
	@Autowired EntityManager entityManager;
	
	public BigDecimal getAmount(Teacher teacher, LocalDate beginDate, LocalDate endDate) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		
		CriteriaQuery<BigDecimal> cq = cb.createQuery(BigDecimal.class);
		Root<TeacherLessonPremium> root = cq.from(TeacherLessonPremium.class);
		Join<TeacherLessonPremium, CourseDetail> courseDetailJoin = root.join("courseDetail");
		
		cq.select(cb.sum(root.<BigDecimal>get("premiumAmount")))
			.where(
					cb.and(
						cb.between(root.<LocalDate>get("billingDate"), beginDate, endDate),
						cb.equal(courseDetailJoin.<Teacher>get("teacher"), teacher)
					));
		BigDecimal amount = entityManager.createQuery(cq).getSingleResult();
		
		if (amount == null) {
			amount = BigDecimal.ZERO;
		}
		
		return amount;
	}
	
	public BigDecimal getAmountInDay(Teacher teacher, LocalDate date) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		
		CriteriaQuery<BigDecimal> cq = cb.createQuery(BigDecimal.class);
		Root<TeacherLessonPremium> root = cq.from(TeacherLessonPremium.class);
		Join<TeacherLessonPremium, CourseDetail> courseDetailJoin = root.join("courseDetail");
		
		cq.select(cb.sum(root.<BigDecimal>get("premiumAmount")))
			.where(cb.equal(root.<LocalDate>get("billingDate"), date), 
					cb.equal(courseDetailJoin.<Teacher>get("teacher"), teacher));
		BigDecimal amount = entityManager.createQuery(cq).getSingleResult();
		
		if (amount == null) {
			amount = BigDecimal.ZERO;
		}
		
		return amount;
	}
	
}
